package com.klm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.klm.dao.TranslatePlatformUsageDao;
import com.klm.entity.TranslatePlatformUsageEntity;
import com.klm.service.TranslatePlatformUsageService;
import com.klm.service.TranslatePlatformCacheService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TranslatePlatformUsageServiceImpl implements TranslatePlatformUsageService {

    private final TranslatePlatformUsageDao usageDao;
    private final TranslatePlatformCacheService cacheService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordUsage(String platformCode, long bytes) {
        // 先更新缓存
        TranslatePlatformUsageEntity cachedUsage = cacheService.getCachedUsage(platformCode);
        if (cachedUsage == null) {
            cachedUsage = new TranslatePlatformUsageEntity();
            cachedUsage.setPlatformCode(platformCode);
            cachedUsage.setUsageDate(LocalDate.now());
            cachedUsage.setTotalBytes(bytes);
            cachedUsage.setTotalRequests(1);
        } else {
            cachedUsage.setTotalBytes(cachedUsage.getTotalBytes() + bytes);
            cachedUsage.setTotalRequests(cachedUsage.getTotalRequests() + 1);
        }
        cacheService.cacheUsage(cachedUsage);

        // 更新数据库
        LambdaUpdateWrapper<TranslatePlatformUsageEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(TranslatePlatformUsageEntity::getPlatformCode, platformCode)
                .eq(TranslatePlatformUsageEntity::getUsageDate, LocalDate.now())
                .setSql("total_bytes = total_bytes + " + bytes)
                .setSql("total_requests = total_requests + 1");
        int updated = usageDao.update(null, wrapper);
        if (updated == 0) {
            // 如果更新失败，说明今天还没有记录，插入新记录
            TranslatePlatformUsageEntity newUsage = new TranslatePlatformUsageEntity();
            newUsage.setPlatformCode(platformCode);
            newUsage.setUsageDate(LocalDate.now());
            newUsage.setTotalBytes(bytes);
            newUsage.setTotalRequests(1);
            usageDao.insert(newUsage);
        }
    }

    @Override
    public TranslatePlatformUsageEntity getTodayUsage(String platformCode) {
        // 先从缓存获取
        TranslatePlatformUsageEntity cachedUsage = cacheService.getCachedUsage(platformCode);
        if (cachedUsage != null) {
            return cachedUsage;
        }
        // 缓存未命中，从数据库获取
        LambdaQueryWrapper<TranslatePlatformUsageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TranslatePlatformUsageEntity::getPlatformCode, platformCode)
                .eq(TranslatePlatformUsageEntity::getUsageDate, LocalDate.now());
        return usageDao.selectOne(wrapper);
    }

    @Override
    public TranslatePlatformUsageEntity getUsageByDate(String platformCode, LocalDate date) {
        LambdaQueryWrapper<TranslatePlatformUsageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TranslatePlatformUsageEntity::getPlatformCode, platformCode)
                .eq(TranslatePlatformUsageEntity::getUsageDate, date);
        return usageDao.selectOne(wrapper);
    }

    @Override
    public List<TranslatePlatformUsageEntity> getUsageByDateRange(String platformCode, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<TranslatePlatformUsageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TranslatePlatformUsageEntity::getPlatformCode, platformCode)
                .between(TranslatePlatformUsageEntity::getUsageDate, startDate, endDate)
                .orderByAsc(TranslatePlatformUsageEntity::getUsageDate);
        return usageDao.selectList(wrapper);
    }

    @Override
    public long getTotalBytesByDateRange(String platformCode, LocalDate startDate, LocalDate endDate) {
        // TODO: 需要实现日期范围内的字节数统计
        return 0;
    }

    @Override
    public int getTotalRequestsByDateRange(String platformCode, LocalDate startDate, LocalDate endDate) {
        // TODO: 需要实现日期范围内的请求次数统计
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetUsage(String platformCode) {
        // 删除缓存
        cacheService.removeCachedUsage(platformCode);
        
        // 删除数据库记录
        LambdaQueryWrapper<TranslatePlatformUsageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TranslatePlatformUsageEntity::getPlatformCode, platformCode);
        usageDao.delete(wrapper);
    }

    @Override
    public void checkAndResetAllPlatforms() {
        // TODO: 需要实现检查并重置所有需要重置的平台
    }
}
